package com.appkubes.mall.restful.application.goods.sku.controller;

import com.alibaba.fastjson.JSONObject;
import com.appkubes.cloud.config.params.paramValid.ParamValid;
import com.appkubes.common.Response;
import com.appkubes.mall.core.entity.MallGoodsSpecific;
import com.appkubes.mall.core.entity.MallGoodsSpecificSku;
import com.appkubes.mall.core.entity.MallSpecificAttribute;
import com.appkubes.mall.core.entity.MallSpecificType;
import com.appkubes.mall.restful.application.common.base.BaseController;
import com.appkubes.mall.restful.application.goods.sku.entity.dto.GoodsSkuDTO;
import com.appkubes.mall.restful.application.goods.sku.entity.vo.MallSpecificTemplateVo;
import com.appkubes.mall.restful.application.goods.sku.entity.vo.SkuVo;
import com.appkubes.mall.restful.application.goods.sku.model.AttributeModel;
import com.appkubes.mall.restful.application.goods.sku.model.SkuItem;
import com.appkubes.mall.restful.application.goods.sku.model.TypeModel;
import com.appkubes.mall.restful.application.goods.sku.service.GoodsSpecificSkuService;
import com.appkubes.mall.restful.application.goods.sku.service.impl.GoodsSpecificServiceImpl;
import com.appkubes.mall.restful.application.goods.sku.service.impl.SpecificAttributeServiceImpl;
import com.appkubes.mall.restful.application.goods.sku.service.impl.SpecificTypeServiceImpl;
import com.appkubes.mall.restful.common.constant.RentOrderPeriodCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

@Api(tags = "多规格")
@RestController
@RequestMapping("/specifictemplate")
public class SpecificTemplateController extends BaseController {

    @Autowired
    SpecificTypeServiceImpl specificTypeServiceImpl;

    @Autowired
    SpecificAttributeServiceImpl specificAttributeServiceImpl;

    @Resource
    GoodsSpecificServiceImpl goodsSpecificServiceImpl;

    @Resource
    GoodsSpecificSkuService goodsSpecificSkuService;

    @ApiOperation("获取模板")
    @PostMapping("/getTemplate")
    public Response getTemplate(@RequestBody @ParamValid MallSpecificTemplateVo mallSpecificTemplateVo) {
        List<MallGoodsSpecific> mallGoodsSpecificList = goodsSpecificServiceImpl.getList(mallSpecificTemplateVo.getKey());
        if (mallGoodsSpecificList.size() == 0) {
            return Response.error("获取不到模板");
        }
        MallGoodsSpecific mallGoodsSpecific = mallGoodsSpecificList.get(0);
        if (StringUtils.isEmpty(mallGoodsSpecific.getSpecificData())) {
            return Response.error("格式错误");
        }
        List<GoodsSkuDTO> goodsSkuDTOList = JSONObject.parseArray(mallGoodsSpecific.getSpecificData(), GoodsSkuDTO.class);
        List<TypeModel> typeModelList = new ArrayList<>();
        for (GoodsSkuDTO goodsSkuDTO : goodsSkuDTOList) {
            TypeModel typeModel = new TypeModel();
            typeModel.setName(goodsSkuDTO.getName());
            typeModel.setPluginRef(goodsSkuDTO.getRef());

            List<AttributeModel> attributeModelList = new ArrayList<>();
            String[] items = goodsSkuDTO.getValues();
            for (String item : items) {

                if ("RENT".equals(typeModel.getPluginRef())) {
                    attributeModelList.add(parseAttr(item));
                } else {
                    AttributeModel attributeModel = new AttributeModel();
                    attributeModel.setName(item);
                    attributeModelList.add(attributeModel);
                }
            }
            typeModel.setItem(attributeModelList);
            typeModelList.add(typeModel);
        }
        return Response.success(typeModelList);
    }

    private AttributeModel parseAttr(String attrName) {
        AttributeModel attributeModel = new AttributeModel();
        attributeModel.setName(attrName);
        if (attrName.contains("周")) {
            attrName = attrName.replace("周", "");
            attributeModel.setPeriods(Integer.valueOf(attrName));
            attributeModel.setUnit("WEEK");
            attributeModel.setCode("WEEK" + attrName);
        }
        if (attrName.contains("月")) {
            attrName = attrName.replace("月", "");
            attributeModel.setPeriods(Integer.valueOf(attrName));
            attributeModel.setUnit("MONTH");
            attributeModel.setCode("MONTH" + attrName);
        }

        if (attrName.contains("年")) {
            attrName = attrName.replace("年", "");
            attributeModel.setPeriods(Integer.valueOf(attrName));
            attributeModel.setUnit("YEAR");
            attributeModel.setCode("YEAR" + attrName);
        }
        return attributeModel;
    }

    private List<TypeModel> buildTyoeModels(List<MallSpecificType> types) {
        List<TypeModel> models = new ArrayList<>();
        for (MallSpecificType type : types) {
            TypeModel model = new TypeModel();
            model.setName(type.getTypeName());
            model.setPluginRef(type.getPluginRef());
            System.out.println("appKey:" + getAppKey());
            List<AttributeModel> attributeModels = specificAttributeServiceImpl.getList(getAppKey(), type.getSpecificTypeKey());
            if ("RENT".equals(type.getPluginRef())) {
                for (AttributeModel attributeModel : attributeModels) {
                    RentOrderPeriodCode rentOrderPeriodCode = RentOrderPeriodCode.valueOf(attributeModel.getCode());
                    attributeModel.setPeriods(rentOrderPeriodCode.getPeriods());
                    attributeModel.setUnit(parseUnit(rentOrderPeriodCode.getPeriodType()));
                }
            }
            model.setItem(attributeModels);
            models.add(model);
        }
        return models;
    }

    private String parseUnit(Integer periodType) {
        String type = "";
        switch (periodType) {
            case 1:
                type = "DAY";
                break;
            case 2:
                type = "WEEK";
                break;
            case 3:
                type = "MONTH";
                break;
            case 4:
                type = "YEAR";
                break;
            default:
                break;
        }
        return type;
    }

    @ApiOperation("获取商品租赁的最小租期")
    @PostMapping("getPluginMiniAttr")
    public Response getPluginMiniAttr(@RequestParam(defaultValue = "") String templateKey) {
        MallSpecificType type = specificTypeServiceImpl.findByPluginCode(templateKey, "RENT");
        if (type == null) {
            return Response.error();
        }
        MallSpecificAttribute attribute = specificAttributeServiceImpl.getFirstAttr(type.getSpecificTypeKey());
        if (attribute == null) {
            return Response.error();
        }
        return Response.success(attribute);
    }

    @ApiOperation("获取skuList")
    @PostMapping("/getSkuList")
    public Response getSkuList(@RequestBody @Valid SkuVo skuVo, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return Response.error("参数错误");
        }
        List<MallGoodsSpecific> mallGoodsSpecificList = goodsSpecificServiceImpl.getList(skuVo.getGoodsKey());
        if (mallGoodsSpecificList == null) {
            return Response.error();
        }
        List<SkuItem> skuItemList = new ArrayList<>();

        MallGoodsSpecific mallGoodsSpecific = mallGoodsSpecificList.get(0);
        if (StringUtils.isEmpty(mallGoodsSpecific.getSpecificDim1())) {
            return Response.success(skuItemList);
        }
        List<GoodsSkuDTO> goodsSkuDTOList = JSONObject.parseArray(mallGoodsSpecific.getSpecificData(), GoodsSkuDTO.class);
        GoodsSkuDTO dim1 = JSONObject.parseObject(mallGoodsSpecific.getSpecificDim1(), GoodsSkuDTO.class);
        GoodsSkuDTO dim2 = JSONObject.parseObject(mallGoodsSpecific.getSpecifcDim2(), GoodsSkuDTO.class);
        GoodsSkuDTO dim3 = JSONObject.parseObject(mallGoodsSpecific.getSpecifcDim3(), GoodsSkuDTO.class);
        GoodsSkuDTO dim4 = JSONObject.parseObject(mallGoodsSpecific.getSpecificDim4(), GoodsSkuDTO.class);
        StringBuilder dimStr = new StringBuilder().append(dim1.getName());
        if (dim2 != null) {
            dimStr.append("-"+dim2.getName());
        }
        if (dim3 != null) {
            dimStr.append("-"+dim3.getName());
        }
        if (dim4 != null) {
            dimStr.append("-"+dim4.getName());
        }
        List<MallGoodsSpecificSku> mallGoodsSpecificSkuList = goodsSpecificSkuService.getList(skuVo.getGoodsKey(), dimStr.toString());
        for (MallGoodsSpecificSku mallGoodsSpecificSku : mallGoodsSpecificSkuList) {
            List<Object[]> dataList = new ArrayList<Object[]>();
            String[] skuCode = mallGoodsSpecificSku.getSkuCode().split("-");
            for (GoodsSkuDTO goodsSkuDTO : goodsSkuDTOList) {
                if ("specific_dim1".equals(goodsSkuDTO.getSku())) {
                    Object[] objects = new Object[]{skuCode[0]};
                    dataList.add(objects);
                } else if ("specific_dim2".equals(goodsSkuDTO.getSku())) {
                    Object[] objects = new Object[]{skuCode[1]};
                    dataList.add(objects);
                } else if ("specific_dim3".equals(goodsSkuDTO.getSku())) {
                    Object[] objects = new Object[]{skuCode[2]};
                    dataList.add(objects);
                } else if ("specific_dim4".equals(goodsSkuDTO.getSku())) {
                    Object[] objects = new Object[]{skuCode[3]};
                    dataList.add(objects);
                } else {
                    Object[] objects = goodsSkuDTO.getValues();
                    dataList.add(objects);
                }
            }
            List<Object[]> a = combination(dataList, 0, null);

            //输出循环结果，生成前端适配的skuList
            for (int i = 0; i < a.size(); i++) {
                Object[] objArr = a.get(i);
                StringBuilder diffrence = new StringBuilder();
                for (Object obj : objArr) {
                    diffrence.append(obj).append(",");
                }
                String diffrenceStr = diffrence.toString();
                diffrenceStr = diffrenceStr.substring(0, diffrenceStr.length() - 1);

                SkuItem skuItem = new SkuItem();
                skuItem.setPrice(mallGoodsSpecificSku.getSkuPrice());
                skuItem.setPic(mallGoodsSpecificSku.getSkuPic());
                skuItem.setOriginPrice(mallGoodsSpecificSku.getSkuOriginalPrice());
                skuItem.setStock(mallGoodsSpecificSku.getSkuStock());
                skuItem.setDifference(objArr);
                skuItem.setSpecificData(diffrenceStr);
                skuItemList.add(skuItem);
            }
        }
        return imgResponse(skuItemList);
    }

    public static List<Object[]> combination(List<Object[]> dataList, int index, List<Object[]> resultList) {
        if (index == dataList.size()) {
            return resultList;
        }
        List<Object[]> resultList0 = new ArrayList<Object[]>();
        if (index == 0) {
            Object[] objArr = dataList.get(0);
            for (Object obj : objArr) {
                resultList0.add(new Object[]{obj});
            }
        } else {
            Object[] objArr = dataList.get(index);
            for (Object[] objArr0 : resultList) {
                for (Object obj : objArr) {
                    //复制数组并扩充新元素
                    Object[] objArrCopy = new Object[objArr0.length + 1];
                    System.arraycopy(objArr0, 0, objArrCopy, 0, objArr0.length);
                    objArrCopy[objArrCopy.length - 1] = obj;

                    //追加到结果集
                    resultList0.add(objArrCopy);
                }
            }
        }
        return combination(dataList, ++index, resultList0);
    }
}
